var SychiInitFlag = false;
var SysjmInitFlag = false;

var chiTitle = [
    {field: "ck", checkbox: true},
    {field: "pro1", title: "定点医疗机构编号", hide: true},
    {field: "pro2", title: "个人编号"},
    {field: "pro3", title: "门诊(住院)流水号", sort: true},
    {field: "pro4", title: "单据号", sort: true},
    {field: "pro5", title: "交易类型", sort: true},
    {field: "pro29", title: "结算时间", sort: true},
    {field: "pro6", title: "医院交易流水号", sort: true},
    {field: "pro7", title: "中心交易流水号", sort: true},
    {field: "pro8", title: "医疗费总额", sort: true},
    {field: "pro9", title: "本次帐户支付"},
    {field: "pro10", title: "统筹支付金额"},
    {field: "pro11", title: "大病救助基金支付", hide: true},
    {field: "pro12", title: "公务员补助支付", hide: true},
    {field: "pro13", title: "离休统筹支付", hide: true},
    {field: "pro14", title: "1-6级伤残军人统筹支付", hide: true},
    {field: "pro15", title: "医院负担金额", hide: true},
    {field: "pro16", title: "本次现金支付"},
    {field: "pro17", title: "自费费用", hide: true},
    {field: "pro18", title: "乙类自理费用", hide: true},
    {field: "pro19", title: "特检自理费用", hide: true},
    {field: "pro20", title: "特治自理费用", hide: true},
    {field: "pro21", title: "起付标准自付", hide: true},
    {field: "pro22", title: "进入统筹费用", hide: true},
    {field: "pro23", title: "统筹分段自付", hide: true},
    {field: "pro24", title: "进入救助金费用", hide: true},
    {field: "pro25", title: "救助金自付", hide: true},
    {field: "pro26", title: "超封顶线自付", hide: true},
    {field: "pro27", title: "符合基本医疗费用", hide: true},
    {field: "pro28", title: "住院次数", hide: true},
    {title: '操作', templet: '#barDemo', fixed: "right", align: "center"}
];

var sjmTitle = [{field: "ck", checkbox: true},
    {field: "pro1", title: "就诊编号", sort: true},
    {field: "pro2", title: "个人编号", sort: true},
    {field: "pro3", title: "结算编号", sort: true},
    {field: "pro4", title: "支付类别"},
    {field: "pro27", title: "结算时间", hide: true},
    {field: "pro5", title: "参保所属机构", hide: true},
    {field: "pro6", title: "清算类别", hide: true},
    {field: "pro7", title: "清算分中心", hide: true},
    {field: "pro8", title: "医疗费总额", sort: true},
    {field: "pro9", title: "全自费金额", hide: true},
    {field: "pro10", title: "超限价自付金额", hide: true},
    {field: "pro11", title: "先行自付金额", hide: true},
    {field: "pro12", title: "符合范围部分", hide: true},
    {field: "pro13", title: "本次起付线"},
    {field: "pro14", title: "实际支付起付线", hide: true},
    {field: "pro15", title: "基本医疗基金支付", hide: true},
    {field: "pro16", title: "基本医疗比例自付", hide: true},
    {field: "pro17", title: "大病保险基金支出", hide: true},
    {field: "pro18", title: "民政救助支付"},
    {field: "pro19", title: "精准扶贫补充医疗支付", hide: true},
    {field: "pro20", title: "个人账户支出", hide: true},
    {field: "pro21", title: "精准扶贫提高金额（基本医疗）", hide: true},
    {field: "pro22", title: "五免费用总额", hide: true},
    {field: "pro23", title: "医院负担部分"},
    {field: "pro24", title: "个人现金支出"},
    {field: "pro25", title: "基金支付金额总计", hide: true},
    {field: "pro26", title: "本次个人账户支付后帐户余额", hide: true},
    {field: "pro28", title: "医疗人员类别", hide: true},
    {field: "pro29", title: "执行社会保险办法", hide: true},
    {title: '操作', minWidth: 50, templet: '#barDemo', fixed: "right", align: "center"}
];

layui.use(['form', 'table', 'layer', 'laydate'], function () {
    var $ = layui.jquery,
        form = layui.form,
        table = layui.table,
        layer = layui.layer,
        laydate = layui.laydate;


    var myDate = new Date();
    myDate.setDate(myDate.getDate() - 7);
    laydate.render({
        elem: '#startDate'
        , theme: '#393D49',
        calendar: true,
        min: '2019-09-27',
        value: myDate
    });


    laydate.render({
        elem: '#endDate'
        , theme: '#393D49',
        calendar: true,
        min: '2019-09-27',
        value: new Date()
    });

    //监听退费
    table.on('tool(test)', function (obj) {
        var data = obj.data;
        if (obj.event === 'del') {

            Swal.fire({
                title: '确定退费 个人编号为:' + data.pro2 + ' 总费用为:' + data.pro8 + ' 的交易么？',
                text: "确认后将会把钱退回医保卡账户中!",
                icon: 'warning',
                showCancelButton: true,
                confirmButtonColor: '#3085d6',
                cancelButtonColor: '#d33',
                confirmButtonText: '确定!',
                cancelButtonText: '不想退了'
            }).then((result) => {
                if (result.value) {
                    pulginObj.call(data);
                }
            });


        }
    });

    // 监听搜索操作
    $("#btn").click(function () {
        //var result = JSON.stringify(data.field);
        layer.msg('后台调用医保接口中...', {
            icon: 16
            , shade: 0.08,
            time: 0
        });

        var str = "test";
        var startDate = $("#startDate").val();
        var endDate = $("#endDate").val();
        var yblx = $("#yblx").val();
        var columns;
        var yblx = $("#yblx").val();
        if (yblx == '42030002') {
            columns = sjmTitle;
        } else {
            endDate = getNewDay(endDate, 1);
            columns = chiTitle;
        }
        $.ajax({
            url: "/hwn/queryUnilateral",
            type: "POST",
            data: {
                startDate: startDate,
                endDate: endDate,
                yblx: yblx,
                str: str
            },
            timeout: 0,
            //async:false,
            success: function (result) {
                console.info(result);
                layer.closeAll();
                if (result.code == '0') {
                    if (result.data.length > 0) {

                    } else {
                        layer.msg('当前条件下,无单边数据...', {time: 3000, icon: 1});
                    }
                    table.render({
                        elem: '#test',
                        //'/hwn/queryUnilateral'
                        data: result.data,
                        toolbar: true, //开启头部工具栏，并为其绑定左侧模板,
                        defaultToolbar: ['filter', 'exports', 'print'],
                        cols: [columns],
                        page: true,
                        cellMinWidth: 80,
                        height: 'full-180',
                        limits: [20, 50, 100, 200],
                        limit: 20
                    })
                } else {
                    layer.alert(result.msg, {
                        title: "系统异常",
                        icon: 2
                    });
                }

            },
            error: function (xhr, msg) {
                layer.alert(xhr.code + " " + msg);
            }
        });

    });

    table.render({
        elem: '#test',
        //'/hwn/queryUnilateral'
        data: [],
        toolbar: true, //开启头部工具栏，并为其绑定左侧模板,
        defaultToolbar: ['filter', 'exports', 'print'],
        cols: [chiTitle],
        page: true,
        cellMinWidth: 80,
        size: 'sm',
        skin: 'line',
        height: 'full-160',
        limits: [20, 50, 100, 200],
        limit: 20
    });

    pulginObj = {
        call: function (row) {
            var flag = false;
            var yblx = $("#yblx").val();
            var jysr = "";
            var jybh = "";
            var result;
            if (row) {
                if (yblx == '42030002') {
                    jybh = '42';
                    jysr += "<?xml version='1.0' encoding='GBK' standalone='yes' ?>";
                    jysr += "<input>";
                    jysr += "<akc190>" + row.pro1 + "</akc190>";
                    jysr += "<aaz216>" + row.pro3 + "</aaz216>";
                    jysr += "<aac001>" + row.pro2 + "</aac001>";
                    jysr += "<aka130>" + row.pro4 + "</aka130>";
                    jysr += "<ykb065>" + row.pro29 + "</ykb065>";
                    jysr += "<aae011>" + "单边处理" + "</aae011>";
                    jysr += "<ykc141>" + "单边处理" + "</ykc141>";
                    jysr += "<aae013>" + "单边处理" + "</aae013>";
                    jysr += "</input>";

                    try {
                        result = JSON.parse(window.parent.SysjmCall(jybh, jysr));
                        if (result.resultSet[0].Code != '1') {
                            Swal.fire({
                                icon: 'error',
                                title: '退费失败...',
                                text: result.resultSet[0].Msg
                            });
                        } else {
                            Swal.fire(
                                '退费成功!',
                                '请查看患者医保卡余额.',
                                'success'
                            )
                        }
                    } catch (e) {
                        Swal.fire({
                            icon: 'warning',
                            title: '调用医保交易失败...',
                            text: "请检查检查浏览器版本是否正确,是否安装医保环境," + e.toLocaleString()
                        });
                    }

                } else {
                    var tcq = "";
                    if (yblx == "42030001") {
                        tcq = "12103";
                    } else if (yblx == "42030011") {
                        tcq = "42038101004";
                    }

                    const swalWithBootstrapButtons = Swal.mixin({
                        customClass: {
                            confirmButton: 'layui-btn layui-btn-normal',
                            cancelButton: 'layui-btn'
                        },
                        buttonsStyling: false
                    })

                    swalWithBootstrapButtons.fire({
                        title: '请选择读卡方式',
                        icon: 'warning',
                        showCancelButton: true,
                        confirmButtonText: '无卡读卡',
                        cancelButtonText: '有卡读卡',
                        reverseButtons: true
                    }).then((result) => {
                        if (result.value) {
                            //无卡读卡
                            return Swal.fire({
                                title: '输入患者身份证号',
                                input: 'text',
                                inputAttributes: {
                                    autocapitalize: 'off'
                                },
                                showCancelButton: true,
                                confirmButtonText: '确认',
                                showLoaderOnConfirm: true,
                                preConfirm: (login) => {
                                    return JSON.parse(window.parent.SychiCall('1410', tcq, login + '||'));

                                },
                                allowOutsideClick: () => !Swal.isLoading()
                            }).then((result) => {
                                if (result.value.resultSet[0].result != 'ok') {
                                    Swal.fire({
                                        icon: 'error',
                                        title: '读卡失败！',
                                        text: result.value.resultSet[0].jyscMsg
                                    })
                                } else {
                                    jybh = '2430';
                                    jysr = row.pro3 + "|" + row.pro4 + "|" + row.pro29 + "|0|||99999|0|||";
                                    try {
                                        result = JSON.parse(window.parent.SychiCall(jybh, tcq, jysr));
                                        if (result.resultSet[0].result != 'ok') {
                                            Swal.fire({
                                                icon: 'error',
                                                title: '退费失败...',
                                                text: result.resultSet[0].jyscMsg
                                            });
                                        } else {
                                            Swal.fire(
                                                '退费成功!',
                                                '请查看患者医保卡余额.',
                                                'success'
                                            )
                                        }
                                    } catch (e) {
                                        Swal.fire({
                                            icon: 'warning',
                                            title: '调用医保交易失败...',
                                            text: "请检查检查浏览器版本是否正确,是否安装医保环境," + e.toLocaleString()
                                        });
                                    }
                                }
                            })
                        } else if (
                            /* Read more about handling dismissals below */
                            result.dismiss === Swal.DismissReason.cancel
                        ) {
                            //有卡读卡
                            result = JSON.parse(window.parent.SychiCall('2100', tcq, ''));
                            if (result.resultSet[0].Code != '1') {
                                Swal.fire({
                                    icon: 'error',
                                    title: '读卡失败...',
                                    text: result.resultSet[0].jyscMsg
                                });
                            } else {
                                jybh = '2430';
                                jysr = row.pro3 + "|" + row.pro4 + "|" + row.pro29 + "|0|||99999|0|||";
                                try {
                                    result = JSON.parse(window.parent.SychiCall(jybh, tcq, jysr));
                                    if (result.resultSet[0].Code != '1') {
                                        Swal.fire({
                                            icon: 'error',
                                            title: '退费失败...',
                                            text: result.resultSet[0].jyscMsg
                                        });
                                    } else {
                                        Swal.fire(
                                            '退费成功!',
                                            '请查看患者医保卡余额.',
                                            'success'
                                        )
                                    }
                                } catch (e) {
                                    Swal.fire({
                                        icon: 'warning',
                                        title: '调用医保交易失败...',
                                        text: "请检查检查浏览器版本是否正确,是否安装医保环境," + e.toLocaleString()
                                    });
                                }
                            }
                        }
                    })


                }
            } else {
                layer.alert('请先选择退费数据！！！');
            }
            return flag;
        },
        query: function (data) {
            //sleep(1000);
            var yblx = data.yblx;
            var startDate = data.startDate;
            var endDate = data.endDate;
            var timestamp = new Date().getTime();
            var qybm = "";
            var jysr = "";
            var jybh = "1100";
            var bxbf = data.bxbf;
            var strJson;
            if (yblx == "42030002") {
                jybh = '46';
                jysr += "<?xml version='1.0' encoding='GBK' standalone='yes' ?>";
                jysr += "<input>";
                jysr += "<aae030>" + startDate + "</aae030>";
                jysr += "<aae031>" + endDate + "</aae031>";
                jysr += "<ykb065>" + bxbf + "</ykb065>";
                jysr += "<outputfile>D:\log\jsxx_" + bxbf + "_" + startDate + "_" + endDate + ".txt</outputfile>";
                jysr += "</input>";
            } else {
                if (yblx == "42030001") {
                    qybm = "12103";
                }
                if (yblx == "42030011") {
                    qybm = "42038101004";
                }
                jysr = "1100^" + qybm + "^10882^^" + formatDate(timestamp) + "^0000^" + startDate.replace("-", "").replace("-", "") + "|" + endDate.replace("-", "").replace("-", "") + "|^";
                var argJson = {"commandSet": [{"areaCode": qybm, "jybh": jybh, "jysrParam": jysr}]};
                strJson = {"action": "SY_JINBAO_CALL", "args": argJson};
            }
            var jysc = $("#jysc");
            var jxflag = true;
            //var jysrstr = jysr.textbox('getValue');
            var str = "";
            try {
                if (yblx) {
                    str = '{"jybh":' + jybh + ',"jysr":"' + jysr + '","jxflag":' + jxflag + ',"InsuranceCode":"' + yblx + '"}';
                } else {
                    layer.alert("交易输入或交易编号不能为空...");
                    return;
                }
                console.info(str);

                // {"action":"SY_JINBAO_CALL","args":{"params":{"filePath": "","actionUrl": ""},
                //      "commandSet":[{"areaCode":"12103","jybh":"1100","jysrParam":"1100^12103^10882^^20191204231641^0000^20191202|20191204|^"}]}}
                //   var argJson = {"commandSet": [{"Jybh": jybh, "JysrXml": jysr}]};
                //
                //   var strJson = {"action": "SYPMEDICARE_CALL", "args": argJson};
                console.info(strJson);
                console.info(JSON.stringify(strJson));
                $.ajax({
                    url: "http://192.168.127.95:8088",
                    type: "POST",
                    data: JSON.stringify(strJson),
                    success: function (result) {
                        console.info(result);
                    },
                    error: function (xhr, msg) {
                        layer.alert(xhr.code + " " + msg);
                    }
                })

                var resultJson = plugin().syncExecute(JSON.stringify(strJson));
                //   alert(result);
                console.info(resultJson);
                //var result = pulginObj.pulgin().onExecute(str);
                //sleep(10000);
                // disLoad();
                //替换文本中的制表符，换行符
                // result = result.replace(/\t/g, "\\t").replace(/\r\n/g, "\\r\\n");
                console.info(resultJson);
                var jsonObj = JSON.parse(resultJson);
                var result = JSON.parse(jsonObj.args);
                console.info(result.resultSet[0].code);
                if (result.resultSet[0].Code != '1') {
                    layer.alert("医保返回交易失败," + result.resultSet[0].Msg);
                } else {
                    var strs = new Array();
                    strs = jsonObj.resultString.split(/\r\n/);
                    var str = '{"total":' + (strs.length - 1).toString() + ',"rows":[';
                    for (var i = 0; i < strs.length - 1; i++) {
                        var strs1 = new Array();
                        strs1 = strs[i].split(/\t/);
                        str += "{";
                        for (var j = 0; j < strs1.length; j++) {
                            if (j != strs1.length - 1) {
                                str += '"pro' + (j + 1).toString() + '":"' + strs1[j] + '",';
                            } else {
                                str += '"pro' + (j + 1).toString() + '":"' + strs1[j] + '"';
                            }
                        }
                        if (i != strs.length - 2) {
                            str += "},";
                        } else {
                            str += "}";
                        }
                    }
                    str += "]}";
                    console.info(str);
                    return str;

                    // $('#tt').datagrid({data:JSON.parse(str)});
                    //doSearch(jsonObj.resultString);
                }
                //jysc.textbox('setValue', result);
            } catch (e) {
                layer.alert('系统异常,' + e.message);
            } finally {

            }
        },

    }
    ;


//时间格式转换
    function formatDate(inputTime) {
        var date = new Date(inputTime);
        var y = date.getFullYear();
        var m = date.getMonth() + 1;
        m = m < 10 ? ('0' + m) : m;
        var d = date.getDate();
        d = d < 10 ? ('0' + d) : d;
        var h = date.getHours();
        h = h < 10 ? ('0' + h) : h;
        var minute = date.getMinutes();
        var second = date.getSeconds();
        minute = minute < 10 ? ('0' + minute) : minute;
        second = second < 10 ? ('0' + second) : second;
        return "" + y + m + d + h + minute + second;
    }

    function getNewDay(dateTemp, days) {
        var dateTemp = dateTemp.split("-");
        var nDate = new Date(dateTemp[1] + '-' + dateTemp[2] + '-' + dateTemp[0]); //转换为MM-DD-YYYY格式
        var millSeconds = Math.abs(nDate) + (days * 24 * 60 * 60 * 1000);
        var rDate = new Date(millSeconds);
        var year = rDate.getFullYear();
        var month = rDate.getMonth() + 1;
        if (month < 10) month = "0" + month;
        var date = rDate.getDate();
        if (date < 10) date = "0" + date;
        return (year + "-" + month + "-" + date);
    }
});









